const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// import CleanWebpackPlugin from 'clean-webpack-plugin';
const CleanWebpackPlugin = require('clean-webpack-plugin');

var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// import { WebpackBundleSizeAnalyzerPlugin } from 'webpack-bundle-size-analyzer';
// var WebpackBundleSizeAnalyzerPlugin = require('webpack-bundle-size-analyzer').WebpackBundleSizeAnalyzerPlugin;
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// Create multiple instances
const extractCSS = new ExtractTextPlugin('css/[name]-one.css');
const extractLESS = new ExtractTextPlugin('css/[name]-two.css');

// const css_loader = "css-loader?modules&localIdentName=[path][name]---[local]---[hash:base64:5]"
const css_loader = "css-loader?modules&minimize&localIdentName=[path][name]---[local]";//https://github.com/webpack-contrib/css-loader#minimize

const webpackConfig = {
    entry: {
        vendor: ["react", "react-dom"],
        babel: ['babel-polyfill'],
        app: path.resolve(__dirname, './src/index.js')
    },
    // entry: path.resolve(__dirname, './src/index.js'),//这里也可以直接写index.1.less，但是也会生成一个js文件
    output: { // 这样写，不会把index.js放到js下，而是把所有文件都放在js下了
        path: path.resolve(__dirname, 'dist/js/'),
        filename: 'index.js'
    },

    output: {
        filename: 'js/[name]-[chunkhash].js',
        chunkFilename: 'js/[name]-[chunkhash].js',
        path: path.resolve(__dirname, './dist'),
        publicPath: './',
    },

    module: {
        // webpack3.x不用loaders，用rules
        // loaders: [
        //     {
        //         test: /\.json$/,
        //         loader: 'json-loader',
        //     },
        //     {
        //         test: /\.less$/,
        //         loaders: ['style-loader', css_loader, 'less-loader'],//1.x的版本是不需要加 "-loader"的，现在用的是3.x版本，需要加
        //     },
        //     {
        //         test: /\.jsx?$/,
        //         loader: 'babel-loader',
        //         exclude: [/node_modules/, './www/comm/public'],
        //     }
        // ],

        rules: [
            {
                test: /\.less$/i,
                use: extractCSS.extract([css_loader, 'less-loader'])
            },
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['react']
                    }
                }
            }
        ],
    },
    devtool: "#source-map",

    plugins: [
        extractCSS, extractLESS,
        new webpack.HashedModuleIdsPlugin(),
        new CleanWebpackPlugin(path.resolve(__dirname, 'dist')),
        // new webpack.optimize.CommonsChunkPlugin({
        //     name: "vendor",
        //     filename: "vendor.js",
        //     // (给 chunk 一个不同的名字)

        //     minChunks: Infinity,
        //     // (随着 entry chunk 越来越多，
        //     // 这个配置保证没其它的模块会打包进 vendor chunk)
        // }),

        new webpack.optimize.CommonsChunkPlugin({
            names: ['vendor', 'babel'],
            filename: 'js/[name]-[chunkhash].js',
        }),


        //2.x和3.x的配置是不一样的
        new UglifyJSPlugin({//https://doc.webpack-china.org/plugins/uglifyjs-webpack-plugin/
            sourceMap: true,//只有设置了devtool才会生效
            beautify: true,//2.x要放在这里
            uglifyOptions: {
                sourceMap: true,
                ie8: false,
                ecma: 8,
                parse: {},
                mangle: false,//不混淆名字
                mangle: {
                    keep_fnames: true,
                    keep_classnames: true,
                    properties: {//https://github.com/mishoo/UglifyJS2/tree/harmony#mangle-properties-options
                        // mangle property options
                        debug: true
                    },
                    beautify: true,
                },
                output: {
                    comments: false,
                    beautify: true,//3.x要放这里
                    keep_quoted_props: true,
                },
                // compress: {//https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options
                //     unused: true,
                //     dead_code: true,
                //     warnings: false,
                //     pure_funcs: ['console.log'],
                //     drop_console: true,
                //     drop_debugger: true,
                //     join_vars: false,
                //     collapse_vars: false,
                // },
                warnings: false
            }

        }),
        // new BundleAnalyzerPlugin(),
        // new WebpackBundleSizeAnalyzerPlugin(path.join(__dirname,'./reports/plain-report.txt')),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'src', 'index.html'),
            hash: false,
            filename: 'index.html',
            inject: 'body',
        }),
        new BundleAnalyzerPlugin({
            // Can be `server`, `static` or `disabled`.
            // In `server` mode analyzer will start HTTP server to show bundle report.
            // In `static` mode single HTML file with bundle report will be generated.
            // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
            analyzerMode: 'static',
            // Host that will be used in `server` mode to start HTTP server.
            analyzerHost: '127.0.0.1',
            // Port that will be used in `server` mode to start HTTP server.
            analyzerPort: 8888,
            // Path to bundle report file that will be generated in `static` mode.
            // Relative to bundles output directory.
            reportFilename: path.resolve(__dirname, './dist/report.html'),
            // Module sizes to show in report by default.
            // Should be one of `stat`, `parsed` or `gzip`.
            // See "Definitions" section for more information.
            defaultSizes: 'parsed',
            // Automatically open report in default browser
            openAnalyzer: true,
            // If `true`, Webpack Stats JSON file will be generated in bundles output directory
            generateStatsFile: true,
            // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
            // Relative to bundles output directory.
            statsFilename: 'js/stats.json',
            // Options for `stats.toJson()` method.
            // For example you can exclude sources of your modules from stats file with `source: false` option.
            // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
            statsOptions: null,
            // Log level. Can be 'info', 'warn', 'error' or 'silent'.
            logLevel: 'info'
        })
    ],
    stats: "verbose",
}


module.exports = webpackConfig;
